package com.hrms.intercept;

import com.hrms.annotation.EmployeeIgnore;
import com.hrms.entity.Employee;
import com.hrms.service.EmployeeService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import java.lang.annotation.Annotation;

@Component
public class EmployeeInterceptor implements HandlerInterceptor {
    // 员工端的拦截器

    @Autowired
    private EmployeeService employeeService;

    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
            throws Exception {
        HandlerMethod handlerMethod = (HandlerMethod) handler;
        Annotation ignore =  handlerMethod.getMethodAnnotation(EmployeeIgnore.class);
        // 不拦截
        if(ignore != null) {
            return true;
        }

        Employee employee = new Employee();
        employee.setEmployee_id(Integer.valueOf(request.getHeader("Employee-Id")));
        employee.setEmployee_status("在线");
        if(!employeeService.checkStatue(employee)) {
            // 置状态码为401
            System.out.println("401");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
            return false;
        }

        return true;
    }
}
